package logic

import (
	"context"

	"book/service/shorturl/cmd/rpc/internal/svc"
	"book/service/shorturl/cmd/rpc/shorturl"
	"book/service/shorturl/model"

	"github.com/tal-tech/go-zero/core/hash"
	"github.com/tal-tech/go-zero/core/logx"
)

type ShortenLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewShortenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ShortenLogic {
	return &ShortenLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ShortenLogic) Shorten(in *shorturl.ShortenReq) (*shorturl.ShortenResp, error) {
	key := hash.Md5Hex([]byte(in.Url))[:6]

	_, err := l.svcCtx.ShorturlModel.FindOneByShorten(key)
	switch err {
	case model.ErrNotFound:
		_, err_insert := l.svcCtx.ShorturlModel.Insert(&model.Shorturl{
			Shorten: key,
			Url:     in.Url,
		})
		if err_insert != nil {
			return nil, err_insert
		}
	}

	return &shorturl.ShortenResp{
		Shorten: key,
	}, nil
}
